package com.example.demo.controller;

import java.io.File;
import java.util.Arrays;
import java.util.UUID;

import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.util.R;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping("/upload")
@Api(value = "文件上传", tags = "文件上传")
public class UploadController {

  @PostMapping("/author_avatar")
  @ApiOperation(value = "作者头像上传")
  public R uploadAuthorAvatar(@ApiParam(value = "文件") @RequestHeader("file") MultipartFile file) {
    // 空文件
    if (file.isEmpty()) {
      return R.fail("请选择文件");
    }

    // 解析文件属性
    String name = file.getOriginalFilename();
    String size = String.format("%.2f", (double) file.getSize() / 1024 / 1024) + "MB";
    String fileType = file.getContentType();
    String[] types = { "image/jpg", "image/png", "image/jpeg", "image/webp" };

    boolean flag = Arrays.asList(types).contains(fileType);
    if (!flag) {
      return R.fail("只能上传图片文件");
    }

    // 新文件名
    String fileName = UUID.randomUUID().toString() + name.substring(name.lastIndexOf("."));

    String filePath = "";
    try {
      filePath = ResourceUtils.getURL("classpath:").getPath() + "static/img/upload/";

      // 判断文件夹是否存在
      File dir = new File(filePath);
      if (!dir.exists()) {
        dir.mkdirs();
      }

      filePath += fileName;

      file.transferTo(new File(filePath));

    } catch (Exception e) {
      e.printStackTrace();

      return R.fail("上传失败");
    }

    JSONObject data = new JSONObject();
    data.put("originName", name);
    data.put("size", size);
    data.put("fileName", fileName);
    data.put("filePath", "/img/upload/" + fileName);

    return R.success(data);
  }

}
